package com.example.hello.controller;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.example.hello.common.Result;
import com.example.hello.dto.LoginRequest;
import com.example.hello.dto.LoginResponse;
import com.example.hello.entity.Employee;
import com.example.hello.service.EmployeeService;
import com.example.hello.util.JwtUtil;

import jakarta.validation.Valid;

/**
 * 登录控制器
 */
@RestController
@RequestMapping("/api")
@CrossOrigin(origins = "*")
public class LoginController {
    
    @Autowired
    private EmployeeService employeeService;
    
    @Autowired
    private JwtUtil jwtUtil;
    
    /**
     * 员工登录接口
     * @param loginRequest 登录请求
     * @return 登录结果
     */
    @PostMapping("/login")
    public Result<LoginResponse> login(@Valid @RequestBody LoginRequest loginRequest) {
        try {
            // 验证员工ID和手机号
            Employee employee = employeeService.validateLogin(
                loginRequest.getEmployeeId(), 
                loginRequest.getPhone()
            );
            
            if (employee == null) {
                return Result.error("员工ID或手机号错误");
            }
            
            // 生成JWT令牌
            String token = jwtUtil.generateToken(employee.getId(), employee.getEmployeeId());
            
            // 构建登录响应
            LoginResponse loginResponse = new LoginResponse(
                employee.getId(),
                employee.getEmployeeId(),
                employee.getName(),
                token
            );
            
            return Result.success(loginResponse);
            
        } catch (Exception e) {
            return Result.error("登录失败：" + e.getMessage());
        }
    }
}
